import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from "@/views/LoginView.vue";
import Layout from "@/components/Layout.vue";
import {ElNotification} from "element-plus";
import UserView from "@/views/user/UserView.vue";
import DeptView from "@/views/DeptView.vue";
import SettingView from "@/views/LeaveView.vue";
import RecruitView from "@/views/RecruitView.vue";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'login',
            component: LoginView
        },
        {
            path: '/home',
            name: 'layout',
            component: Layout,
            beforeEnter: (to, from, next) => {

                // 检测 token 是否存在
                try {
                    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                    ElNotification({
                        title: '登录成功',
                        message: '欢迎回来，' + userInfo.username,
                        type: 'success',
                    });
                    next(); // 允许继续路由导航
                } catch (error) {
                    ElNotification({
                        title: '登录失败',
                        message: '用户校验失败，请重新登录',
                        type: 'error',
                    });
                    router.push({name: 'login'});
                }
            },
            children: [
                {
                    path: '/home',
                    name: 'home',
                    component: HomeView
                },
                {
                    path: '/user',
                    name: '/user',
                    component: UserView
                },
                {
                    path: '/dept',
                    name: 'dept',
                    component: DeptView
                },
                {
                    path: '/setting',
                    name: 'setting',
                    component: SettingView
                },
                {
                    path: '/recruit',
                    name:'recruit',
                    component: RecruitView
                }
            ]
        }
    ]
})

export default router
